package com.ruoyi.result.patents.service.impl;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sql.SqlUtil;
import com.ruoyi.result.papers.domain.ResultPapers;
import com.ruoyi.result.papers.domain.vo.ResultPapersVO;
import com.ruoyi.result.patents.domain.Patents;
import com.ruoyi.result.patents.domain.ResultPatents;
import com.ruoyi.result.patents.domain.dto.ResultPatentsDTO;
import com.ruoyi.result.patents.domain.vo.ResultPatentsVO;
import com.ruoyi.result.patents.mapper.ResultPatentsMapper;
import com.ruoyi.result.patents.service.IResultPatentsService;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserPostMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.team.trash.domain.AchievementTrash;
import com.ruoyi.team.trash.mapper.AchievementTrashMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 专利信息Service业务层处理
 *
 * @author ruoyi
 * @date 2025-01-14
 */
@Service
public class ResultPatentsServiceImpl implements IResultPatentsService
{
    @Autowired
    private ResultPatentsMapper resultPatentsMapper;

    @Autowired
    private SysUserPostMapper sysUserPostMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private AchievementTrashMapper achievementTrashMapper;
    /**
     * 查询专利信息
     *
     * @param id 专利信息主键
     * @return 专利信息
     */
    @Override
    public ResultPatents selectResultPatentsById(Long id)
    {
        return resultPatentsMapper.selectResultPatentsById(id);
    }

    /**
     * 批量获取专利详细信息
     */
    @Override
    public List<ResultPatentsVO> selectResultPatentsByIds(Long[] ids) {
        if (ids == null || ids.length == 0) {
            return Collections.emptyList();
        }
        List<ResultPatents> resultPatentsList = resultPatentsMapper.selectResultPatentsByIds(ids);
        List<ResultPatentsVO> resultPatentsVOList = new ArrayList<>();
        for (ResultPatents resultPatent : resultPatentsList) {
            ResultPatentsVO resultPatentsVO = new ResultPatentsVO();
            // 假设 resultPatent 和 resultPatentsVO 有相同的字段，先进行复制
            BeanUtils.copyProperties(resultPatent, resultPatentsVO);

            // 根据 userId 查询 nick_name
            SysUser sysUser = sysUserMapper.selectUserById(resultPatent.getUserId());
            resultPatentsVO.setNickName(sysUser.getNickName());

            resultPatentsVOList.add(resultPatentsVO);
        }
        return resultPatentsVOList;
    }

    /**
     * 查询专利信息列表
     *
     * @param resultPatents 专利信息
     * @return 专利信息
     */
    /**
     * 查询专利信息列表
     *
     * @param resultPatents 专利信息
     * @return 专利信息
     */
    @Override
    public TableDataInfo selectResultPatentsList(ResultPatentsDTO resultPatents) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long deptId = loginUser.getUser().getDeptId();

        // 判断是否为超级管理员（若依默认超级管理员用户ID为1）
        boolean isSuperAdmin = loginUser.getUser().getUserId().equals(1L);

        // 非超级管理员才进行部门过滤
        if (!isSuperAdmin) {
            resultPatents.setDeptId(deptId);
        }

        // 分页处理
        PageDomain pageDomain = TableSupport.buildPageRequest();
        if (StringUtils.isNotNull(pageDomain.getPageNum()) && StringUtils.isNotNull(pageDomain.getPageSize())) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageDomain.getPageNum(), pageDomain.getPageSize(), orderBy)
                    .setReasonable(pageDomain.getReasonable());
        }

        // 查询专利列表（根据部门过滤）
        List<ResultPatents> resultPatentsList = resultPatentsMapper.selectResultPatentsListByDept(resultPatents);

        // 组装 VO
        List<ResultPatentsVO> resultPatentsVOList = resultPatentsList.stream().map(p -> {
            ResultPatentsVO vo = new ResultPatentsVO();
            BeanUtils.copyProperties(p, vo);
            SysUser sysUser = sysUserMapper.selectUserById(p.getUserId());
            if (sysUser != null) {
                vo.setNickName(sysUser.getNickName());
            }
            return vo;
        }).collect(Collectors.toList());

        // 返回结果
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setTotal(new PageInfo<>(resultPatentsList).getTotal());
        rspData.setRows(resultPatentsVOList);

        return rspData;
    }




    /**
     * 新增专利信息
     *
     * @param resultPatents 专利信息
     * @return 结果
     */
    @Override
    public int insertResultPatents(ResultPatents resultPatents)
    {
        return resultPatentsMapper.insertResultPatents(resultPatents);
    }

    /**
     * 修改专利信息
     *
     * @param resultPatents 专利信息
     * @return 结果
     */
    @Override
    public int updateResultPatents(ResultPatents resultPatents)
    {
        return resultPatentsMapper.updateResultPatents(resultPatents);
    }

    /**
     * 批量删除专利信息
     *
     * @param ids 需要删除的专利信息主键
     * @return 结果
     */
    @Override
    public int deleteResultPatentsByIds(Long[] ids)
    {
        List<ResultPatents> resultPatentsList = resultPatentsMapper.selectResultPatentsByIds(ids);
        for (ResultPatents resultPatents : resultPatentsList) {
            AchievementTrash achievementTrash = new AchievementTrash();
            achievementTrash.setUserid(resultPatents.getUserId());
            achievementTrash.setAchievementType("专利");
            achievementTrash.setTitle(resultPatents.getTitle());
            achievementTrash.setAchievementId(resultPatents.getId());
            achievementTrash.setDeletedAt(new Date());
            achievementTrashMapper.insertAchievementTrash(achievementTrash);
        }
        return resultPatentsMapper.deleteResultPatentsByIds(ids);
    }

    /**
     * 删除专利信息信息
     *
     * @param id 专利信息主键
     * @return 结果
     */
    @Override
    public int deleteResultPatentsById(Long id)
    {
        return resultPatentsMapper.deleteResultPatentsById(id);
    }

    /**
     * 根据专利id主键查看专利
     * @param id
     * @return
     * @throws IllegalArgumentException 如果id为null
     */
    @Override
    public Patents getPatentsById(Long id) {
        if (id == null) {
            throw new IllegalArgumentException("专利ID不能为空");
        }

        Patents patents = resultPatentsMapper.selectPatentsById(id);
        if (patents == null) {
            // 可以选择抛出异常或返回一个默认值
            throw new NoSuchElementException("未找到ID为" + id + "的专利");
        }

        return patents;
    }
}
